<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />

    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        name="用户名"
        label="手机号码"
        required
        placeholder="手机号码"
        :rules="[
          {
            required: true,
            message: '请填写正确的手机号',
            trigger: 'onChange',
            pattern: /^1[3-9]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        name="密码"
        label="登录密码"
        required
        placeholder="登录密码"
        :rules="[
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          loading-text="加载中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { MyNotify } from '@/utils/MyNotify.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      // username: '',
      // password: ''
      formLogin: {
        mobile: '18888888888',
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),

    // 点击登录
    async onSubmit () {
      this.isLoading = true // 按钮加载效果
      try {
        const res = await loginAPI(this.formLogin)
        const { token, refresh_token } = res.data.data// 解构赋值
        this.setToken(token)
        this.setRefreshToken(refresh_token)

        console.log('获取成功')
        console.log(res)
        MyNotify({ type: 'success', message: '想我的荀荀老婆' })
        this.isLoading = false // 关闭加载的动画效果
        this.$router.replace({ // 成功登录跳转到layout页面
          path: '/layout'
        })
      } catch {
        // 即使登陆失败 也要把加载按钮放开
        console.log('获取失败')
        this.isLoading = false
        MyNotify({ type: 'warning', message: '差点意思' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
